﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.TeamFoundation.Build.Client;
using Microsoft.TeamFoundation.Build.Workflow.Activities;
using System.IO;
using Microsoft.TeamFoundation.Build.Workflow.Tracking;

namespace NDependActivities
{
    [BuildActivity(HostEnvironmentOption.All)]
    public sealed class NDependDataLog : CodeActivity
    {
        /// <summary>
        /// Le seul argument de notre activité est le chemin vers le rapport NDepend
        /// </summary>
        public InArgument<string> ReportPath { get; set; }

        public InArgument<string> ReportLink { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            string reportPath = ReportPath.Get(context);

            if (String.IsNullOrEmpty(reportPath))
            {
                context.TrackBuildWarning("No NDepend report specified.");
            }
            else
            {
                if (!File.Exists(reportPath))
                {
                    context.TrackBuildError("NDepend report file " + reportPath + " not found");
                }
                else
                {
                    var reader = new NDependReportReader(reportPath);
                    
                    var reportContainer = reader.GetReportInfo();
                    

                    context.Track(new BuildInformationRecord<NDependReportInfo>
                    {
                        Value = reportContainer.ReportInfo
                    });

                    foreach (NDependCriticalRuleInfo criticalRuleInfo in reportContainer.CriticalRules)
                    {
                        context.TrackBuildMessage(criticalRuleInfo.Name, BuildMessageImportance.Normal);

                        context.Track(new BuildInformationRecord<NDependCriticalRuleInfo>
                        {
                            Value = criticalRuleInfo
                        });
                    }

                    context.Track(new BuildInformationRecord<NDependReportLink>()
                    {
                        Value = new NDependReportLink { Url = ReportLink.Get(context) }
                    });

                    context.TrackBuildMessage("Report file successfully processed");
                }
            }
        }
    }
}
